import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

class MyTimer{
    PriorityQueue<MyTimerTsak> queue = new PriorityQueue<>();
    Object locker = new Object();
    public MyTimer(){
            Thread t = new Thread(() -> {
                synchronized (locker) {
                    while (true) {
                        try {
                            while (queue.isEmpty()) {
                                locker.wait();
                            }
                            MyTimerTsak current = queue.peek();
                            if (System.currentTimeMillis() >= current.getTime()) {
                                current.run();
                                queue.poll();
                            } else {
                                locker.wait(current.getTime() - System.currentTimeMillis());
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            t.start();
        }
    public void schedle(Runnable runnable,long time){
        synchronized (locker) {
            MyTimerTsak myTimerTsak = new MyTimerTsak(runnable, time);
            queue.offer(myTimerTsak);
            locker.notify();
        }
    }
}
class MyTimerTsak implements Comparable<MyTimerTsak>{
    private Runnable runnable;
    private long time;
    public MyTimerTsak(Runnable runnable,long time){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }
    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTsak o) {
        return (int) (this.time - o.time);
    }
}

public class Demo {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedle(()->{
            System.out.println(3);
        },3000);
        myTimer.schedle(()->{
            System.out.println(1);
        },1000);
        myTimer.schedle(()->{
            System.out.println(2);
        },2000);
    }

}
